package com.cws4cloud.cws.mall.file.biz.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cws4cloud.cws.common.core.constant.ComponentConstant;
import com.cws4cloud.cws.common.core.util.R;
import com.cws4cloud.cws.common.oss.core.OssTemplate;
import com.cws4cloud.cws.common.oss.props.OssProperties;
import com.cws4cloud.cws.common.oss.util.OssUtil;
import com.cws4cloud.cws.mall.file.api.entity.Attachment;
import com.cws4cloud.cws.mall.file.biz.mapper.AttachmentMapper;
import com.cws4cloud.cws.mall.file.biz.service.AttachmentService;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 附件表
 *
 * @author zhulj
 * @date 2021-01-28 11:29:25
 */
@Service
@RequiredArgsConstructor
public class AttachmentServiceImpl extends ServiceImpl<AttachmentMapper, Attachment> implements AttachmentService {

	private final RedisTemplate<String, Object> redisTemplate;

	private final OssTemplate ossTemplate;

	@Value("${oss.enabled:false}")
	private boolean ossEnabled;
	/**
	 * 本地图片上传路径
	 */
	@Value(value = "${file.upload.path:/work/cws/image}")
	private String path;

	@Override
	public R upload(MultipartFile file) {
		OssProperties ossProperties = getOssProperties();
		String fileName = UUID.randomUUID().toString().replace("-", "")
				+ StringPool.DOT + FilenameUtils.getExtension(file.getOriginalFilename());
		Map<String, String> uMap = new HashMap<>(4);
		long size = file.getSize();
		String original = file.getOriginalFilename();
		String originalName = FilenameUtils.getName(original);
		try {
			String url = "";
			if (ossEnabled) {
				//上传文件
				assert ossProperties != null;
				ossTemplate.putObject(ossProperties.getBucketName(), fileName, file.getInputStream(), file.getSize(), file.getContentType());
				//生成URL
				url = "https://" + ossProperties.getCustomDomain() + StringPool.SLASH + fileName;
				//自定义返回报文

				uMap.put("bucketName", ossProperties.getBucketName());
				uMap.put("fileName", fileName);
				uMap.put("url", url);

			} else {
				url = uploadSingleFile(file, null, fileName);
				uMap.put("originalName", originalName);
				uMap.put("fileName", fileName);
				uMap.put("url", url);
			}
			//上传成功后记录入库
			this.attachmentLog(original, originalName, size, url, fileName);
		} catch (Exception e) {
			log.error("上传失败", e);
			return R.failed(e.getMessage());
		}
		return R.ok(uMap);
	}

	/**
	 * 将上传成功的文件记录入库
	 * @param file　文件
	 * @param url　返回的URL
	 * @return boolean
	 */
	public boolean attachmentLog(MultipartFile file, String url, String fileName) {
		Attachment attachment = new Attachment();
		String original = file.getOriginalFilename();
		String originalName = FilenameUtils.getName(original);
		attachment.setName(originalName);
		attachment.setUrl(url);
		attachment.setFileName(fileName);
		attachment.setSize(file.getSize());
		attachment.setType(OssUtil.getFileType(original));
		return this.save(attachment);
	}

	/**
	 * 将上传成功的文件记录入库
	 * @param file　文件
	 * @param url　返回的URL
	 * @return boolean
	 */
	public boolean attachmentLog(String original,String originalName,long fileSize, String url, String fileName) {
		Attachment attachment = new Attachment();
		attachment.setName(originalName);
		attachment.setUrl(url);
		attachment.setFileName(fileName);
		attachment.setSize(fileSize);
		attachment.setType(OssUtil.getFileType(original));
		return this.save(attachment);
	}

	/**
	 * 从redis里读取OssProperties
	 * @return OssProperties
	 */
	public OssProperties getOssProperties(){
		return (OssProperties) redisTemplate.opsForValue().get(ComponentConstant.OSS_DEFAULT);
	}

	/**
	 * 本地文件服务图片上传【上传到本地硬盘】
	 *
	 * @return
	 */
	private String uploadSingleFile(MultipartFile multipartFile, String fileUrl, String fileName) throws IOException {
		//判断url是否为空，如果为空，使用默认
		if (StrUtil.isEmpty(fileUrl)) {
			fileUrl = "/admin-api/common/image";
		}
		String oldName = multipartFile.getOriginalFilename();
		//获取扩展名，默认是jpg
		String expandedName = FilenameUtils.getExtension(oldName);
		String newPath = path + "/" + expandedName + "/" + DateUtil.thisYear() + "/"
				+ DateUtil.thisMonth() + "/" + DateUtil.thisDayOfMonth() + "/";
		String returnUrl = fileUrl + "/" + expandedName + "/" + DateUtil.thisYear() + "/"
				+ DateUtil.thisMonth() + "/" + DateUtil.thisDayOfMonth() + "/" + fileName;
		String saveUrl = newPath + fileName;
		// 保存本地，创建目录
		java.io.File file1 = new java.io.File(newPath);
		if (!file1.exists()) {
			file1.mkdirs();
		}
		java.io.File saveFile = new java.io.File(saveUrl);
		// 序列化文件到本地
//		saveFile.createNewFile();
		multipartFile.transferTo(saveFile);
		return returnUrl;
	}
}
